let zipImage = function (type, options){
	let dstWidth = 800
	if(type === 'avatar'){
		dstWidth = 200
	}else if(typeof type === 'number'){
		dstWidth = type
	}
	return new Promise((resolve, reject)=>{
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'], //从相册,相机选择
			success: function(cimg) {
				let imgPath = cimg.tempFilePaths[0]
				getImageInfo(imgPath).then(res=>{
					let {width, path, height, orientation} = res
					width = Number(width)
					height = Number(height)
					let config = {}
					orientation = orientation.replace('-mirrored', '')
					switch (orientation){
						case 'down': 
							config.rotate = 180
							break;
						case 'left': 
							config.rotate = 90
							break;
						case 'right':
							config.rotate = 270
							break;
					}
					if(type === 'avatar' && width > dstWidth){
						config.clip = {}
						if(width > height){
							let sc = dstWidth / height
							config.height = dstWidth + 'px'
							config.clip.width = dstWidth + 'px'
							config.clip.height = dstWidth + 'px'
							config.clip.left = Math.floor((width * sc - dstWidth) / 2) + 'px'
						}else{
							let sc = dstWidth / width
							config.width = dstWidth + 'px'
							config.clip.height = dstWidth + 'px'
							config.clip.width = dstWidth + 'px'
							config.clip.top = Math.floor((height * sc - dstWidth) / 2) + 'px'
						}
					}else if(dstWidth > width){
						config.width = width
					}else{
						config.width = dstWidth
					}
					editImage(path, config, options).then(editRes=>{
						resolve(editRes)
					})
				}).catch(()=>{
					resolve({code: 4, data: '', msg: '图片信息获取失败'})
				})
			},
			fail: () => {
				resolve({code: 3, data: '', msg: '未选择图片'})
			}
		});
	})
}

function getImageInfo (imgPath){
	return new Promise ((resolve, reject)=>{
		plus.io.getImageInfo({
			src: imgPath,
			success: (res)=>{
				resolve(res)
			},
			error: (err)=>{
				reject(err)
			}
		});
	})
}

function editImage (imgPath, config, config2){
	var newimgName = new Date().getTime() + '.jpg'
	let options = {
		overwrite: true,
		src: imgPath,
		dst: `_doc/${newimgName}`,
		format: "jpg",
		quality: 60,
		width: '800px',
	}
	options = Object.assign(options, config, config2)
	//先缩放、旋转、裁剪
	return new Promise((resolve, reject)=>{
		plus.zip.compressImage(options, ()=> {
			resolve({code: 1, data: `_doc/${newimgName}`})
		}, (error)=> {
			resolve({code: 2, data: '', msg: '裁切失败'})
		});
	})
}

export {zipImage, editImage, getImageInfo}